package com.secondriver.url.filter.match;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class URLCacheObject {

	private static final long ALIVE_TIME = 1800000;

	private static final int MAX_URLBEANS = 30;

	private long aliveTime;

	private URLBean oldURLbean;

	public URLCacheObject() {
		this.setAliveTime(System.currentTimeMillis() + ALIVE_TIME);
	}

	private final Set<URLBean> urlBeanCache = new HashSet<URLBean>(MAX_URLBEANS);

	public boolean isExist(String urlValue) {
		Iterator<URLBean> iter = urlBeanCache.iterator();
		while (iter.hasNext()) {
			URLBean o = iter.next();
			if (o.getUrlValue().equals(urlValue)) {
				o.updateAccessNumbe();
				return true;
			}
		}
		return false;
	}

	public void add(String urlValue) {
		if (urlBeanCache.size() >= MAX_URLBEANS) {
			Iterator<URLBean> iter = urlBeanCache.iterator();
			long min = Long.MAX_VALUE;
			while (iter.hasNext()) {
				URLBean o = iter.next();
				long accessNumber = o.getAccessNumber();
				if (accessNumber < min) {
					oldURLbean = o;
					min = accessNumber;
				}
			}
			oldURLbean.setAccessNumber(1);
			oldURLbean.setUrlValue(urlValue);
		} else {
			URLBean o = new URLBean();
			o.setUrlValue(urlValue);
			urlBeanCache.add(o);
		}
	}

	public long getAliveTime() {
		return aliveTime;
	}

	public void setAliveTime(long aliveTime) {
		this.aliveTime = aliveTime;
	}

	private class URLBean {

		private long accessNumber = 1;
		private String urlValue;

		public long getAccessNumber() {
			return accessNumber;
		}

		public void setAccessNumber(long accessNumber) {
			this.accessNumber = accessNumber;
		}

		public void updateAccessNumbe() {
			this.accessNumber++;
		}

		public String getUrlValue() {
			return urlValue;
		}

		public void setUrlValue(String urlValue) {
			this.urlValue = urlValue;
		}
	}
}
